package com.yuan.base.service.server.filter;

import com.alibaba.fastjson.JSON;
import com.yuan.base.service.common.dto.AppInfo;
import com.yuan.base.service.common.dto.BusinessInfo;
import com.yuan.base.service.infrastructure.AMIC;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import static com.yuan.base.service.common.HeaderConstants.*;

/**
 * @author lintiangang
 * @date 2021/03/26 10:21
 **/
@Slf4j
@Configuration
public class FeignInterceptor implements RequestInterceptor {

    @Value("${spring.profiles.active:prod}")
    private String envTag;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        Long userId = AMIC.getUserId();
        if (userId != null) {
            requestTemplate.header(USER_ID, String.valueOf(userId));
        }

        String traceId = AMIC.getTraceId();
        requestTemplate.header(TRACE_ID, traceId);

        AppInfo appInfo = AMIC.getAppInfo();
        if (appInfo != null) {
            requestTemplate.header(APP_INFO, JSON.toJSONString(appInfo));
        }

        BusinessInfo businessInfo = AMIC.getBusinessInfo();
        if (businessInfo != null) {
            requestTemplate.header(BUSINESS_INFO, JSON.toJSONString(businessInfo));
        }

        if (!envTag.equals("prod")) {
            log.info("add to feign {}, {}, {}, {}", userId, traceId, appInfo, businessInfo);
        }
    }
}
